//
//  LJMMultiLevelTableView.m
//  09-静态单元格
//
//  Created by Sizhu Ba on 2017/9/7.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "LJMMultiLevelTableView.h"
#import "CTMLObj.h"
#import "MLNodelObj.h"

#import "CTMLCHeaderView.h"
#import "CTMLCell.h"

typedef void(^leafObj)();
typedef void(^ResObj)(id obj);

@interface LJMMultiLevelTableView ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray<CTMLObj*> * companys;
@property (nonatomic, strong) NSMutableArray<NSMutableArray<MLNodelObj*>*> * tempNodes;
@property (nonatomic, strong) NSMutableArray<NSIndexPath *> * reloadArray;
@property (nonatomic, copy) leafObj leafblock;
@property (nonatomic, assign) BOOL preservation;  //收起后再展开是否保留之前的展开状态
@property (nonatomic, assign) BOOL isInitializeed;//是否已经初始化过
@end

@implementation LJMMultiLevelTableView

-(instancetype)init:(CGRect)frame andNeedPreservation:(BOOL) needPreservation andObjs:(NSObject *) objs{
    
    self = [super initWithFrame:frame style:UITableViewStyleGrouped];
    
    self.backgroundColor = [UIColor whiteColor];
    self.reloadArray = [NSMutableArray<NSIndexPath *> array];
    
    self.delegate = self;
    
    self.dataSource = self;
    
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self registerClass:CTMLCell.class forCellReuseIdentifier:@"CTMLCell"];
    
    [self registerClass:CTMLCHeaderView.class forHeaderFooterViewReuseIdentifier:@"CTMLCHeader"];
    
    
    self.isInitializeed = true;
    self.tempNodes = [NSMutableArray<NSMutableArray<MLNodelObj*>*> array];
    
    
    if (objs !=nil) {
        self.companys = (NSMutableArray<CTMLObj*> *) objs;
        
    }
    for (CTMLObj* obj in self.companys) {
        [self.tempNodes addObject:[NSMutableArray<MLNodelObj*> array]];
    }
    NSLog(@"数量是%ld",[self.tempNodes count]);
    self.preservation = needPreservation;
    
    return self;
    
}

-(void)reloadNode:(NSObject *)nodes {
    if (!self.isInitializeed){
        return;
    }
    self.companys = (NSMutableArray<CTMLObj*>*) nodes;
    [self.tempNodes removeAllObjects];
    [self.reloadArray removeAllObjects];
    for (CTMLObj* obj in self.companys) {
        [self.tempNodes addObject:[NSMutableArray<MLNodelObj*> array]];
    }
    [self reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.companys.count;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    // NSLog(@"无法发现的id%ld", self.tempNodes[section].count);
    return   self.tempNodes[section].count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CTMLCHeaderView *head = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"CTMLCHeader"];
    CTMLObj * comobj = self.companys[section] ;
    [head setInfo:comobj];
    head.tap = ^(id obj) {
        
        comobj.isopen = !comobj.isopen;
        if (comobj.isopen) {
            [self expandNodes:section andParentID:comobj.ownID andIndex:-1];
        
        }else{
             [self.tempNodes[section] removeAllObjects];
        }
        
         [self.reloadArray removeAllObjects];
        //NSLog(@"获取数据%@",[[NSIndexSet alloc]initWithIndex:section]);
        
        [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
        
        
    };
    return head;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  50;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CTMLCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CTMLCell" forIndexPath:indexPath];
    MLNodelObj * obj = self.tempNodes[indexPath.section][indexPath.row];
    [cell setcellinfo:obj];
    
    return  cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MLNodelObj *  currentnode = self.tempNodes[indexPath.section][indexPath.row];
    if (currentnode.leaf){
       //  print("点击叶子,\(currentnode.name)");
        NSLog(@"%@",@"点击叶子");
        NSLog(@"叶子的名字是%@",currentnode.name);
        self.rule.text = [NSString stringWithFormat:@"选择的积分规则是: %@",currentnode.name]; 
        if (self.leafblock !=nil) {
            self.leafblock();
        }
        return;
    } else {
        currentnode.expand =!currentnode.expand;
        
    }
    [self.reloadArray removeAllObjects];
    
    if (currentnode.expand) {
        
         [self expandNodes:indexPath.section andParentID:currentnode.ownID andIndex:indexPath.row];
        //插入cell
        
        [tableView insertRowsAtIndexPaths:self.reloadArray withRowAnimation:UITableViewRowAnimationNone];
    }else{
        
        
        [self foldNodes:indexPath.section andLeve:currentnode.level andCurrentIndex:indexPath.row];
        //删除cell
        
        
        [tableView deleteRowsAtIndexPaths:self.reloadArray withRowAnimation:UITableViewRowAnimationNone];
        
    }
    //刷新这行cell的显示
    NSArray<NSIndexPath *> * indexPaths = [NSArray<NSIndexPath *> arrayWithObject:indexPath];
    
    [tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}
/**
 * 这里有误
 */
-(NSInteger)expandNodes:(NSInteger) section andParentID:(NSString *) parentID andIndex:(NSInteger) index{
    NSInteger  insertindex = index;
    
    for(int i= 0;i<self.companys[section].subNodes.count; i++){
        
        MLNodelObj * node = self.companys[section].subNodes[i];
        //找到父节点是parentID的子节点
        if ([node.parentID isEqualToString: parentID]) {
            if (!self.preservation){
                node.expand = false;
            }
            //展开节点的后面+1的位置
            insertindex += 1;
            //根据展开顺序排列
            
            [self.tempNodes[section] insertObject:node atIndex:insertindex];
            [self.reloadArray addObject:[NSIndexPath indexPathForRow:insertindex inSection:section]];
            //NSLog(@"插入存储数据的量%ld",[self.reloadArray count]);
            //遍历子节点的子节点进行展开
            if (node.expand) {
               
                insertindex = [self expandNodes:section andParentID:node.ownID andIndex:insertindex];
            }
        }
    }
    return insertindex;
}
-(void)foldNodes:(NSInteger)section andLeve:(NSInteger) level andCurrentIndex:(NSInteger) currentIndex {
    
    if (currentIndex+1<self.tempNodes[section].count) {
        NSArray *  tempArr = [NSArray arrayWithArray:self.tempNodes[section]];
        NSInteger startI = currentIndex+1;
        NSInteger endI = currentIndex;
        
        for (NSInteger i = currentIndex+1; i< tempArr.count ; i++){
            //  let node = tempArr[i] as! MLNodelObj
            MLNodelObj *node = (MLNodelObj *)tempArr[i];
            if (node.level <= level) {
                break;
                
            }else {
                endI += 1;
                [self.reloadArray addObject:[NSIndexPath indexPathForRow:i inSection:section]];
            }
        }
        
        if (endI >= startI) {
            
          
           [self.tempNodes[section] removeObjectsInRange: NSMakeRange (startI, endI-startI+1)];
        }
    }
    
}


@end

